//
//  WmcHomeVC+PhotoCombine.swift
//  YPWatermarkCamera
//
//  Created by Json on 2023/7/31.
//  边拍边拼

import Foundation

extension WmcHomeVC {
    
    /// 边拍边拼模式
    func photoCombineMode() {
        // 顶部
        headerView.switchMode(.photoAndCombine, cameraView: cameraView)
        // 中部
        switchMode(.photoAndCombine)
        // 底部
        footerView.switchMode(.photoAndCombine)
        positioningBtn.isHidden = false
    }
    
    /// 拼图数量变化
    func didCombinedPhotoChanged() {
        // 需要拍照总数
        let totalNum = viewModel.combinePhotoSetting.columns.photoNum
        // 已拍照片数量
        let finishedNum = viewModel.combinedPhotos.count
        // 更新footerView
        footerView.combinePhotoTitle = "已拍\(finishedNum)/\(totalNum)"
        footerView.canCombine = finishedNum >= 2
        // 更新布局view
        photoLayoutView.finishCount = finishedNum
        photoLayoutView.reload()
        

    }
    /// 拼图总数发生变化
    private func didChangedCombinePhoto(totalNum: Int) {
        // 已拍照片数量
        let finishedNum = viewModel.combinedPhotos.count
        // 更新footerView
        footerView.combinePhotoTitle = "已拍\(finishedNum)/\(totalNum)"
        // 更新布局view
        photoLayoutView.totalCount = totalNum
        photoLayoutView.reload()
    }
    
    /// 弹出撤销提示弹窗
    func showUndoAlert() {
        let alertView = WmcAlertView()
        alertView.title = "确认撤销上一张照片?"
        alertView.msg = "撤销后不可恢复"
        alertView.style = .custom(confirmTitle: "确定", cancelTitle: "取消")
        alertView.confirmBlock = {
            [weak self] in
            guard let self = self else { return }
            if self.viewModel.combinedPhotos.count <= 1 {
                self.cancelCombinePhoto()
                return
            }
            self.viewModel.combinedPhotos.removeLast()
            self.didCombinedPhotoChanged()
        }
        alertView.show()
    }
    
    /// 取消拼图
    func cancelCombinePhoto() {
        footerView.photoCombineState = .stop
        functionSelectView.isHidden = false
        viewModel.combinedPhotos.removeAll()
        didCombinedPhotoChanged()
    }
    
    /// 获取拍摄的拼图图片之后
    func didGotDisposedCombined(photo: UIImage) {
        // 保存拍摄的照片
        viewModel.combinedPhotos.append(photo)
        // 已拍照片数量
        let finishedNum = viewModel.combinedPhotos.count
        // 总共需要拍摄照片数量
        let totalNum = viewModel.combinePhotoSetting.columns.photoNum
        // 拼图引导
        let guideFinished = viewModel.hasCombinePhotoGuideFinished
        if !guideFinished {
            if finishedNum == 1 { // 拍一张
                footerView.cpGuideState = .stepTwo
                footerView.updateTakePhotoButton()
            } else if finishedNum == 2 { // 拍2张
                // 显示拼图引导
                if totalNum > finishedNum { // 如果总拼图数量大于已拍数量,显示拼图完成引导
                    showCombineGuideView()
                }
                // 结束引导
                finishCombinePhotoGuide()
            }
        }
        // 是否已拍完
        let isFinished = finishedNum >= totalNum
        // 拼图状态
        let state: PhotoCombineState = isFinished ? .stop : .being
        if isFinished { // 已完成拍照数量
            // 开始拼图
            startCombinePhotos()
        } else { // 未完成
            // 开放拍照按钮
            unlockAction()
        }
        // 更新拼图状态
        footerView.photoCombineState = state
        // 拼图数量变化
        didCombinedPhotoChanged()
        // 功能模式切换显示隐藏
        functionSelectView.isHidden = !isFinished
    }
    
    /// 开始拼图
    func startCombinePhotos() {
        viewModel.asynCombinePhotos {
            [weak self] in
            guard let self = self else { return }
            // 停止拼图
            self.didStopCombinePhoto()
            // 清除保存的拼接图片
            self.viewModel.combinedPhotos.removeAll()
            self.didCombinedPhotoChanged()
            // 开放拍照按钮
            self.unlockAction()
            // 可以息屏
            UIApplication.shared.isIdleTimerDisabled = false
        }
    }
    
    /// 结束拼图引导
    func finishCombinePhotoGuide() {
        if footerView.cpGuideState == .none { return }
        footerView.cpGuideState = .none
        footerView.updateTakePhotoButton()
        WmcUserdefault.save(value: true, forKey: .Tips.Home.hasCombinePhotoGuideFinished)
    }
    
    /// 显示拼图引导
    func showCombineGuideView() {
        let titleView = footerView.titleView
        var maskFrame = titleView.convert(titleView.okBtn.frame, to: combineGuideView)
        maskFrame.size.width += 8.0.wmc_autoHor
        combineGuideView.maskFrame = maskFrame
        combineGuideView.maskCornerRadius = 4.0
        combineGuideView.isHidden = false
    }
    
    /// 弹出边拍边拼提示弹窗
    func showPhotoCombineAlert() {
        let alertView = WmcPhotoCombineAlertView()
        var config = WmcPresentVC.Config.basicConfig(view: alertView, style: .alert()) { make in
            make.width.equalTo(320.0.wmc_autoHor)
            make.center.equalToSuperview()
        }
        config.isTouchMaskDismiss = false
        alertView.photoButtonClicked.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            WmcDebug("点击马上拍")
        }).disposed(by: rx.disposeBag)
        alertView.show(config: config)
    }
    
    /// 弹出拼图模板弹窗
    func showPhotoLayoutAlert() {
        let alertView = WmcPhotoLayoutAlertView()
        let setting = viewModel.combinePhotoSetting
        // 模板
        alertView.templateStyle = setting.style
        // 排版
        alertView.layoutColumns = setting.columns
        // 已拍摄照片数量
        alertView.finishedPhotoCount = viewModel.combinedPhotos.count

        let sheetConfig = WmcPresentVC.Style.SheetConfig()
        sheetConfig.isAutoHeight = true
        var config = WmcPresentVC.Config.basicConfig(view: alertView, style: .sheet(sheetConfig)) { make in
            make.left.right.bottom.equalToSuperview()
        }
        config.isTouchMaskDismiss = false
        // 点击更多功能
        alertView.moreAction.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            self.showCombinePhotoFeedbackAlert()
        }).disposed(by: rx.disposeBag)
        // 选中模板回调
        alertView.didSelectedTemplate.subscribe(onNext: {
            [weak self] style in
            guard let self = self else { return }
            WmcDebug("模板==>\(style)")
            self.photoLayoutView.style = style
            self.viewModel.combinePhotoSetting.style = style
            self.viewModel.didChangedCombinePhotoSetting()
        }).disposed(by: rx.disposeBag)
        // 选中排版回调
        alertView.didSelectedLayout.subscribe(onNext: {
            [weak self] columns in
            guard let self = self else { return }
            WmcDebug("排版==>\(columns)")
            self.photoLayoutView.columns = columns.rawValue
            self.photoLayoutView.reload()
            self.viewModel.combinePhotoSetting.columns = columns
            self.viewModel.didChangedCombinePhotoSetting()
        }).disposed(by: rx.disposeBag)
        // 照片数量变化回调
        alertView.photoNumChanged.subscribe(onNext: {
            [weak self] num in
            guard let self = self else { return }
            WmcDebug("拼图总数==>\(num)")
            self.didChangedCombinePhoto(totalNum: num)
        }).disposed(by: rx.disposeBag)
        alertView.show(config: config)
    
    }
    
    /// 弹出拼图功能反馈弹窗
    func showCombinePhotoFeedbackAlert() {
        WmcCombinePhotoFeedbackAlertView.show()
    }
    
    /// 弹出取消拼图弹窗
    func showCancelCombinePhotoAlert() {
        let alert = WmcAlertView()
        alert.title = "提示"
        alert.msg = "确定不保存已拍摄图片?"
        alert.style = .custom(confirmTitle: "确定", cancelTitle: "取消")
        alert.confirmBlock = {
            [weak self] in
            guard let self = self else { return }
            // 停止拼图
            self.didStopCombinePhoto()
            // 取消拼图
            self.viewModel.combinedPhotos.removeAll()
            self.didCombinedPhotoChanged()
            // 结束引导
            self.finishCombinePhotoGuide()
        }
        alert.show()
    }
    
    /// 停止拼图后调用
    func didStopCombinePhoto() {
        footerView.photoCombineState = .stop
        functionSelectView.isHidden = false
    }
    
}
